package org.hepeng.workx.spring.orm.jpa;

import org.apache.commons.collections.MapUtils;
import org.hepeng.workx.spring.orm.TXSyncResourceHolder;
import org.joor.Reflect;
import org.springframework.orm.jpa.EntityManagerHolder;
import org.springframework.transaction.support.TransactionSynchronizationUtils;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import java.util.Map;
import java.util.Objects;

/**
 * @author he peng
 */
public class CrossThreadTransactionalEntityManagerHolder {

    public static EntityManager getTransactionalEntityManager(EntityManagerFactory entityManagerFactory) {
        Map<Object, Object> txSyncResourceMap = TXSyncResourceHolder.get();
        if (MapUtils.isEmpty(txSyncResourceMap)) {
            return null;
        }
        Object actualKey = Reflect.on(TransactionSynchronizationUtils.class)
                .call("unwrapResourceIfNecessary" , entityManagerFactory)
                .get();
        EntityManagerHolder holder = (EntityManagerHolder) txSyncResourceMap.get(actualKey);
        if (Objects.isNull(holder)) {
            return null;
        }
        return holder.getEntityManager();
    }
}
